<template>
  <div class="order-management">
    <div class="header">
      <h2>订单管理</h2>
    </div>

    <!-- 搜索过滤区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="filter-item">
          <label>订单号:</label>
          <input
            v-model="searchParams.orderNo"
            type="text"
            placeholder="输入订单号"
            class="form-input"
            @keyup.enter="loadOrderList"
          />
        </div>
        <div class="filter-item">
          <label>用户ID:</label>
          <input
            v-model.number="searchParams.memberId"
            type="number"
            placeholder="用户ID"
            class="form-input"
            @keyup.enter="loadOrderList"
          />
        </div>
        <div class="filter-item">
          <label>订单状态:</label>
          <select v-model="searchParams.status" class="form-select">
            <option value="">全部状态</option>
            <option value="pending">待支付</option>
            <option value="paid">已支付</option>
            <option value="shipped">已发货</option>
            <option value="completed">已完成</option>
            <option value="cancelled">已取消</option>
          </select>
        </div>

        <div class="filter-actions">
          <button @click="loadOrderList" class="btn btn-info">
            <i class="fas fa-search"></i> 搜索
          </button>
          <button @click="resetSearch" class="btn btn-secondary">
            <i class="fas fa-redo"></i> 重置
          </button>
        </div>
      </div>
    </div>

    <!-- 订单列表表格 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th width="80">订单ID</th>
            <th width="140">订单号</th>
            <th width="80">用户ID</th>
            <th width="120">收货人信息</th>
            <th width="120">支付信息</th>
            <th width="100">订单状态</th>
            <th width="120">收货地址</th>
            <th width="200">备注</th>
            <th width="120">创建时间</th>
            <th width="160">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="order in orderList" :key="order.id">
            <td>{{ order.id }}</td>
            <td class="order-no">
              <strong>{{ order.orderNo }}</strong>
            </td>
            <td>{{ order.memberId }}</td>
            <td class="receiver-info">
              <div v-if="order.receiverName">
                <strong>{{ order.receiverName }}</strong>
                <div v-if="order.receiverPhone" class="phone">{{ order.receiverPhone }}</div>
              </div>
              <span v-else class="no-info">未填写</span>
            </td>
            <td class="payment-info">
              <div class="amount">¥{{ order.totalPay.toFixed(2) }}</div>
              <div v-if="order.payType" class="pay-type">{{ order.payType }}</div>
              <div v-if="order.payTime" class="pay-time">{{ formatDateTime(order.payTime) }}</div>
            </td>
            <td>
              <span :class="['status-badge', `status-${order.status}`]">
                {{ getStatusText(order.status) }}
              </span>
            </td>
            <td class="address-info">
              <div v-if="order.receiverAddrDetail" class="address">
                {{ order.receiverAddrDetail }}
              </div>
              <span v-else class="no-address">未填写</span>
            </td>
            <td class="comment">
              <div v-if="order.orderComment" class="order-comment">{{ order.orderComment }}</div>
              <div v-if="order.description" class="order-desc">{{ order.description }}</div>
            </td>
            <td>{{ formatDateTime(order.createdTime) }}</td>
            <td class="actions">
              <button @click="viewOrder(order)" class="btn btn-sm btn-info">
                <i class="fas fa-eye"></i> 查看
              </button>
              <button 
                v-if="order.status === 'paid'"
                @click="shipOrder(order)" 
                class="btn btn-sm btn-warning"
              >
                <i class="fas fa-truck"></i> 发货
              </button>
              <button 
                v-if="order.status === 'shipped'"
                @click="completeOrder(order)" 
                class="btn btn-sm btn-success"
              >
                <i class="fas fa-check"></i> 完成
              </button>
              <button 
                v-if="['pending', 'paid'].includes(order.status)"
                @click="cancelOrderAction(order)" 
                class="btn btn-sm btn-danger"
              >
                <i class="fas fa-times"></i> 取消
              </button>
            </td>
          </tr>
          <tr v-if="orderList.length === 0">
            <td colspan="10" class="no-data">暂无订单数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-section">
      <div class="pagination-info">
        共 {{ total }} 条记录，第 {{ current }} / {{ Math.ceil(total / pageSize) }} 页
      </div>
      <div class="pagination-controls">
        <button
          @click="changePage(current - 1)"
          :disabled="current <= 1"
          class="btn btn-sm btn-secondary"
        >
          上一页
        </button>
        <span class="page-numbers">
          <button
            v-for="page in getPageNumbers()"
            :key="page"
            @click="changePage(page)"
            :class="['btn', 'btn-sm', page === current ? 'btn-primary' : 'btn-outline']"
          >
            {{ page }}
          </button>
        </span>
        <button
          @click="changePage(current + 1)"
          :disabled="current >= Math.ceil(total / pageSize)"
          class="btn btn-sm btn-secondary"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 订单详情弹窗 -->
    <div v-if="showOrderDetail" class="modal-overlay">
      <div class="modal-content order-detail-modal" @click.stop>
        <div class="modal-header">
          <h3>订单详情</h3>
          <button @click="closeOrderDetail" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <div v-if="selectedOrder" class="order-detail">
            <div class="detail-section">
              <h4>基本信息</h4>
              <div class="detail-row">
                <span class="label">订单号:</span>
                <span class="value">{{ selectedOrder.orderNo }}</span>
              </div>
              <div class="detail-row">
                <span class="label">订单状态:</span>
                <span :class="['value', 'status-badge', `status-${selectedOrder.status}`]">
                  {{ getStatusText(selectedOrder.status) }}
                </span>
              </div>
              <div class="detail-row">
                <span class="label">创建时间:</span>
                <span class="value">{{ formatDateTime(selectedOrder.createdTime) }}</span>
              </div>
              <div class="detail-row">
                <span class="label">用户ID:</span>
                <span class="value">{{ selectedOrder.memberId }}</span>
              </div>
            </div>

            <div class="detail-section">
              <h4>支付信息</h4>
              <div class="detail-row">
                <span class="label">支付金额:</span>
                <span class="value amount">¥{{ selectedOrder.totalPay.toFixed(2) }}</span>
              </div>
              <div class="detail-row">
                <span class="label">支付方式:</span>
                <span class="value">{{ selectedOrder.payType || '未支付' }}</span>
              </div>
              <div v-if="selectedOrder.payTime" class="detail-row">
                <span class="label">支付时间:</span>
                <span class="value">{{ formatDateTime(selectedOrder.payTime) }}</span>
              </div>
            </div>

            <div class="detail-section">
              <h4>收货信息</h4>
              <div class="detail-row">
                <span class="label">收货人:</span>
                <span class="value">{{ selectedOrder.receiverName || '未填写' }}</span>
              </div>
              <div class="detail-row">
                <span class="label">联系电话:</span>
                <span class="value">{{ selectedOrder.receiverPhone || '未填写' }}</span>
              </div>
              <div class="detail-row">
                <span class="label">收货地址:</span>
                <span class="value">{{ selectedOrder.receiverAddrDetail || '未填写' }}</span>
              </div>
            </div>

            <div v-if="selectedOrder.orderComment || selectedOrder.description" class="detail-section">
              <h4>备注信息</h4>
              <div v-if="selectedOrder.orderComment" class="detail-row">
                <span class="label">订单备注:</span>
                <span class="value">{{ selectedOrder.orderComment }}</span>
              </div>
              <div v-if="selectedOrder.description" class="detail-row">
                <span class="label">描述:</span>
                <span class="value">{{ selectedOrder.description }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="closeOrderDetail" class="btn btn-secondary">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { getOrderList, updateOrderStatus, cancelOrder, getOrderStatusStats } from '@/api/order'
import type { Order, OrderSearchParams } from '@/types/order'

// 响应式数据
const orderList = ref<Order[]>([])
const total = ref(0)
const current = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const showOrderDetail = ref(false)
const selectedOrder = ref<Order | null>(null)

// 订单统计
const orderStats = reactive({
  pending: 0,
  paid: 0,
  shipped: 0,
  completed: 0
})

// 搜索参数
const searchParams = reactive<OrderSearchParams>({
  pageNo: 1,
  pageSize: 10,
  orderNo: '',
  memberId: undefined,
  status: ''
})

// 加载订单列表
const loadOrderList = async () => {
  loading.value = true
  try {
    searchParams.pageNo = current.value
    searchParams.pageSize = pageSize.value
    const response = await getOrderList(searchParams)
    orderList.value = response.data.records
    total.value = response.data.total
    
    // 更新统计数据
    await updateOrderStats()
  } catch (error) {
    console.error('加载订单列表失败:', error)
    alert('加载订单列表失败')
  } finally {
    loading.value = false
  }
}

// 更新订单统计
const updateOrderStats = async () => {
  try {
    // 尝试从API获取全局统计数据
    const response = await getOrderStatusStats()
    const stats = {
      pending: response.data.pending || 0,
      paid: response.data.paid || 0,
      shipped: response.data.shipped || 0,
      completed: response.data.completed || 0
    }
    Object.assign(orderStats, stats)
  } catch (error) {
    // 如果API不存在，则通过查询各状态订单数量来获取统计
    console.warn('订单统计API不可用，使用备用方案:', error)
    await loadOrderStatsByQuery()
  }
}

// 备用方案：通过查询获取各状态订单统计
const loadOrderStatsByQuery = async () => {
  const statuses = ['pending', 'paid', 'shipped', 'completed']
  const stats = { pending: 0, paid: 0, shipped: 0, completed: 0 }
  
  try {
    // 并发查询各状态的订单数量
    const promises = statuses.map(async (status) => {
      const response = await getOrderList({
        pageNo: 1,
        pageSize: 1,
        status
      })
      return { status, count: response.data.total }
    })
    
    const results = await Promise.all(promises)
    results.forEach(result => {
      stats[result.status as keyof typeof stats] = result.count
    })
    
    Object.assign(orderStats, stats)
  } catch (error) {
    console.error('获取订单统计失败:', error)
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchParams, {
    orderNo: '',
    memberId: undefined,
    status: ''
  })
  current.value = 1
  loadOrderList()
}

// 分页切换
const changePage = (page: number) => {
  if (page < 1 || page > Math.ceil(total.value / pageSize.value)) return
  current.value = page
  loadOrderList()
}

// 获取分页数字
const getPageNumbers = () => {
  const nums: number[] = []
  const totalPages = Math.ceil(total.value / pageSize.value)
  const start = Math.max(1, current.value - 2)
  const end = Math.min(totalPages, current.value + 2)
  
  for (let i = start; i <= end; i++) {
    nums.push(i)
  }
  return nums
}

// 查看订单详情
const viewOrder = (order: Order) => {
  selectedOrder.value = order
  showOrderDetail.value = true
}

// 关闭订单详情
const closeOrderDetail = () => {
  showOrderDetail.value = false
  selectedOrder.value = null
}

// 发货订单
const shipOrder = async (order: Order) => {
  if (!confirm(`确定要将订单 ${order.orderNo} 标记为已发货吗？`)) return
  
  try {
    await updateOrderStatus(order.id, 'shipped')
    order.status = 'shipped'
    alert('发货成功')
    await updateOrderStats()
  } catch (error) {
    console.error('发货失败:', error)
    alert('发货失败')
  }
}

// 完成订单
const completeOrder = async (order: Order) => {
  if (!confirm(`确定要将订单 ${order.orderNo} 标记为已完成吗？`)) return
  
  try {
    await updateOrderStatus(order.id, 'completed')
    order.status = 'completed'
    alert('订单完成')
    await updateOrderStats()
  } catch (error) {
    console.error('完成订单失败:', error)
    alert('完成订单失败')
  }
}

// 取消订单
const cancelOrderAction = async (order: Order) => {
  if (!confirm(`确定要取消订单 ${order.orderNo} 吗？`)) return
  
  try {
    await cancelOrder(order.id)
    order.status = 'cancelled'
    alert('订单已取消')
    await updateOrderStats()
  } catch (error) {
    console.error('取消订单失败:', error)
    alert('取消订单失败')
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'pending': '待支付',
    'paid': '已支付',
    'shipped': '已发货',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

// 导出订单数据
const exportOrders = () => {
  alert('导出功能开发中...')
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 页面加载时获取数据
onMounted(() => {
  loadOrderList()
})
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  gap: 20px;
  align-items: end;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.filter-item label {
  font-weight: 500;
  color: #555;
  font-size: 12px;
}

.form-input, .form-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.filter-item .form-input,
.filter-item .form-select {
  width: 120px;
}



.stats-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 15px;
  flex: 1;
  min-width: 200px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.stat-icon.pending {
  background: #ffc107;
}

.stat-icon.paid {
  background: #28a745;
}

.stat-icon.shipped {
  background: #17a2b8;
}

.stat-icon.completed {
  background: #6f42c1;
}

.stat-info h3 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.stat-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow-x: auto;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 1200px;
}

.data-table th {
  background: #f8f9fa;
  padding: 12px 8px;
  text-align: left;
  font-weight: 600;
  border-bottom: 2px solid #dee2e6;
  font-size: 12px;
}

.data-table td {
  padding: 12px 8px;
  border-bottom: 1px solid #dee2e6;
  vertical-align: middle;
  font-size: 12px;
}

.order-no strong {
  color: #007bff;
  font-family: monospace;
}

.receiver-info strong {
  display: block;
  color: #333;
  margin-bottom: 2px;
}

.receiver-info .phone {
  color: #666;
  font-size: 11px;
}

.payment-info .amount {
  font-weight: 600;
  color: #28a745;
  font-size: 13px;
  margin-bottom: 2px;
}

.payment-info .pay-type {
  color: #666;
  font-size: 11px;
  margin-bottom: 1px;
}

.payment-info .pay-time {
  color: #999;
  font-size: 10px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 10px;
  font-weight: 500;
}

.status-pending {
  background: #fff3cd;
  color: #856404;
}

.status-paid {
  background: #d4edda;
  color: #155724;
}

.status-shipped {
  background: #cce7ff;
  color: #004085;
}

.status-completed {
  background: #e2e3e5;
  color: #383d41;
}

.status-cancelled {
  background: #f8d7da;
  color: #721c24;
}

.address-info .address {
  color: #333;
  font-size: 11px;
  line-height: 1.3;
}

.no-info, .no-address {
  color: #999;
  font-style: italic;
  font-size: 11px;
}

.comment {
  max-width: 200px;
  overflow: hidden;
}

.order-comment, .order-desc {
  font-size: 11px;
  color: #666;
  line-height: 1.3;
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.actions .btn {
  margin-right: 3px;
  margin-bottom: 3px;
}

.btn {
  padding: 6px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 11px;
  display: inline-flex;
  align-items: center;
  gap: 3px;
  transition: all 0.2s;
}

.btn-sm {
  padding: 3px 6px;
  font-size: 10px;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-info {
  background: #17a2b8;
  color: white;
}

.btn-warning {
  background: #ffc107;
  color: #212529;
}

.btn-success {
  background: #28a745;
  color: white;
}

.btn-danger {
  background: #dc3545;
  color: white;
}

.btn-outline {
  background: transparent;
  border: 1px solid #ddd;
  color: #333;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-numbers {
  display: flex;
  gap: 5px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.order-detail-modal {
  width: 90%;
  max-width: 800px;
}

.modal-content {
  background: #ffffff;
  border-radius: 4px;
  max-height: 90vh;
  overflow-y: auto;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #999999;
  padding: 4px;
  line-height: 1;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #666666;
}

.modal-body {
  padding: 20px;
  background: #ffffff;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 500;
  color: #333333;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 8px;
}

.detail-row {
  display: flex;
  margin-bottom: 8px;
  align-items: flex-start;
}

.detail-row .label {
  font-weight: 400;
  color: #666666;
  width: 100px;
  flex-shrink: 0;
  font-size: 14px;
}

.detail-row .value {
  color: #333333;
  font-size: 14px;
}

.modal-footer {
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
  text-align: right;
  background: #fafafa;
}
</style> 